home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11181 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  57 lines

  1. Path: hopper.acm.org!news
  2. From: varnk@e62.diebold.com (Ken Varn)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: array of struct
  5. Date: 22 Mar 1996 13:33:12 GMT
  6. Organization: Diebold
  7. Message-ID: <4iua6o$ftq@hopper.acm.org>
  8. References: <Pine.LNX.3.91.960319173746.16221A-100000@larry.inf.net>
  9. NNTP-Posting-Host: 199.218.232.47
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=US-ASCII
  12. X-Newsreader: WinVN 0.99.7
  13.  
  14. In article <Pine.LNX.3.91.960319173746.16221A-100000@larry.inf.net>, 
  15. larry@larry.inf.net says...
  16. >
  17. >
  18. >I have a question... though it is petty it bothers me greatly.  :(
  19. >
  20. >How would I create a runtime defined array of struct.
  21. >
  22. >What I want to do is create each record in the array by reading a line 
  23. >from a file and storing each field of the line into the record.  Do this 
  24. >for every line in the file and then where done.  What I need to do is 
  25. >create the array of the struct for the exact number of lines that are in 
  26. >the file.  This way I won't be wasting memory and I won't have to worry 
  27. >about not having enough records to store the lines into.
  28. >
  29.  
  30. You need to use dynamic allocation with malloc() or calloc().  See below.
  31.  
  32.  
  33. typedef struct {
  34.     int var;
  35.     /* whatever else you want in structure. */
  36. } StructureName;
  37.  
  38.  
  39. void main(void)
  40.  
  41. {
  42. StructureName *Structure;
  43. int NumRecs = 10;
  44.  
  45.    Structure = malloc(NumRecs,sizeof(*Structure));
  46.     
  47.    if (Structure == NULL)
  48.       printf("Allocation Failed");
  49.    else
  50.    {
  51.       /* Access structure anyway you want here with array subscripting */
  52.       /* i.e. Structure[0].var = x;
  53.    }
  54. }
  55.  
  56.  
  57.